<script setup lang="ts">
import CustomNavbar from './components/CustomNavbar.vue';
import CategoryPanel from './components/CategoryPanel.vue';
import HotPanel from './components/HotPanel.vue';
import PageSkeleton from './components/PageSkeleton.vue';
import { onLoad } from '@dcloudio/uni-app';
import { getHomeBannerAPI, getHomeCategoryAPI, getHotAPI } from '@/services/home';
import { ref } from 'vue';
import type { BannerItem, CategoryItem, HotItem } from '@/types/home';
import { useGuessList } from '@/composables/index';

const bannerList = ref<BannerItem[]>([]);
const getHomeBannerData = async () => {
  const res = await getHomeBannerAPI();
  bannerList.value = res.result;
};

const categoryList = ref<CategoryItem[]>([]);
const getHomeCategoryData = async () => {
  const res = await getHomeCategoryAPI();
  categoryList.value = res.result;
};

const hotList = ref<HotItem[]>([]);
const getHotData = async () => {
  const res = await getHotAPI();
  hotList.value = res.result;
};

const isLoading = ref(false);
onLoad(async () => {
  isLoading.value = true;
  await Promise.all([getHomeBannerData(), getHomeCategoryData(), getHotData()]);
  isLoading.value = false;
});

// 猜你喜欢滚动触底加载更多
const { guessRef, onScrolltolower } = useGuessList();

// 下拉刷新
const isPull = ref(false);
const onRefresherrefresh = async () => {
  // 下拉刷新动画开始
  isPull.value = true;
  // 重置猜你喜欢组件数据
  guessRef.value?.resetData();
  await Promise.all([
    getHomeBannerData(),
    getHomeCategoryData(),
    getHotData(),
    guessRef.value?.getMore(),
  ]);
  // 下拉刷新动画结束
  isPull.value = false;
};
</script>
<template>
  <!-- 自定义导航栏 -->
  <CustomNavbar />
  <scroll-view
    :refresher-enabled="true"
    @refresherrefresh="onRefresherrefresh"
    :refresher-triggered="isPull"
    @scrolltolower="onScrolltolower"
    class="scroll-view"
    scroll-y
  >
    <PageSkeleton v-if="isLoading" />
    <template v-else>
      <!-- 自定义轮播图 -->
      <XtxSwiper :list="bannerList" />
      <!-- 首页分类 -->
      <CategoryPanel :list="categoryList" />
      <!-- 热门推荐 -->
      <HotPanel :list="hotList" />
      <!-- 猜你喜欢 -->
      <XtxGuess ref="guessRef" />
    </template>
  </scroll-view>
</template>

<style lang="scss">
page {
  background-color: #f7f7f7;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.scroll-view {
  flex: 1;
}
</style>
